package com.chixing.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.chixing.annotation.AutoIdempotent;
import com.chixing.entity.DTO.RefundsDTO;
import com.chixing.entity.OrderDetail;
import com.chixing.entity.OrderTransactions;
import com.chixing.entity.Orders;
import com.chixing.entity.Refunds;
import com.chixing.mapper.OrderDetailMapper;
import com.chixing.mapper.OrderTransactionsMapper;
import com.chixing.mapper.OrdersMapper;
import com.chixing.mapper.RefundsMapper;
import com.chixing.service.IOrderDetailService;
import com.chixing.service.IRefundsService;
import com.chixing.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 酒店订单退款控制器（JDK 17 + 中文状态 + 支付宝退款）
 */
@RestController
@RequestMapping("/refunds")
public class RefundsController {

    @Autowired
    private IRefundsService iRefundsService;

    @Autowired
    private OrderTransactionsMapper orderTransactionsMapper;

    @Autowired
    private RefundsMapper refundsMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private IOrderDetailService iOrderDetailService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 支付宝退款接口（支持全额退款 / 部分退款）
     */
    @PostMapping("/refund")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    @AutoIdempotent
    public Result refund(@RequestBody RefundsDTO refundsDTO) {

        String orderNumber = refundsDTO.getOrderNumber();
        BigDecimal refundAmount = refundsDTO.getRefundAmount();
        String refundReason = refundsDTO.getRefundReason() != null ? refundsDTO.getRefundReason() : "正常退款";

        System.out.println("开始调用支付宝退款接口，订单号 = " + orderNumber + "，退款金额 = " + refundAmount);

        try {
            // 初始化支付宝客户端
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.setServerUrl(com.chixing.config.AlipayConfig.gatewayUrl);
            alipayConfig.setAppId(com.chixing.config.AlipayConfig.app_id);
            alipayConfig.setPrivateKey(com.chixing.config.AlipayConfig.merchant_private_key);
            alipayConfig.setFormat("json");
            alipayConfig.setAlipayPublicKey(com.chixing.config.AlipayConfig.alipay_public_key);
            alipayConfig.setCharset(com.chixing.config.AlipayConfig.charset);
            alipayConfig.setSignType(com.chixing.config.AlipayConfig.sign_type);


            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);

            //生成退款请求号（幂等）
            String outRequestNo = UUID.randomUUID().toString().replace("-", "");

            //构造支付宝退款请求
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(orderNumber);
            model.setRefundAmount(refundAmount.toPlainString());
            model.setRefundReason(refundReason);
            model.setOutRequestNo(outRequestNo);
            request.setBizModel(model);

            //创建退款记录（初始状态：待退款）
            Refunds refundRecord = new Refunds();
            refundRecord.setOrderId(refundsDTO.getOrderId());
            refundRecord.setRefundAmount(refundAmount);
            refundRecord.setRefundReason(refundReason);
            refundRecord.setRefundMethod("原路返回");
            refundRecord.setRefundStatus("待退款");
            refundRecord.setOutRequestNo(outRequestNo);
            refundRecord.setApplyTime(LocalDateTime.now());

            Result result = iRefundsService.CreateRefundsOrder(refundRecord);
            Refunds refunds = (Refunds) result.getData();

            if (refunds == null) {
                return Result.getFail("退款记录创建失败");
            }

            //调用支付宝接口
            AlipayTradeRefundResponse response = alipayClient.execute(request);

            //根据结果更新状态
            if (response.isSuccess()) {
                System.out.println("退款成功, 支付宝交易号: " + response.getTradeNo());

                refunds.setRefundStatus("退款成功");
                refunds.setApproveTime(LocalDateTime.now());
                refunds.setCompleteTime(LocalDateTime.now());
                refundsMapper.updateById(refunds);

                // 获取订单
                Orders orders = ordersMapper.selectById(refunds.getOrderId());
                //获取订单详情
                Result result2 = iOrderDetailService.selectByOrderId(refunds.getOrderId());
                OrderDetail orderDetail = (OrderDetail) result2.getData();

                if (orders == null) {
                    return Result.getFail("订单不存在");
                }

                Double orderAmount = orderDetail.getOrderPrice();
                BigDecimal orderAmountBD = BigDecimal.valueOf(orderAmount);


                // 判断全额退款
                if (refundAmount.compareTo(orderAmountBD) >= 0) {
                    // 全额退款或取消订单
                    orders.setOrderStatus("已取消");
                } else {
                    // 部分退款
                    orders.setOrderStatus("已取消");
                    double newAmount = orderAmountBD.subtract(refundAmount).doubleValue();
                    orderDetail.setOrderPrice(newAmount);
                }

               // 更新订单
                ordersMapper.updateById(orders);
                //更新流水详情
                orderDetailMapper.updateById(orderDetail);


                //生成退款流水
                OrderTransactions refundFlow = new OrderTransactions();
                refundFlow.setOrderId(refundsDTO.getOrderId());
                refundFlow.setTransactionsNo(UUID.randomUUID().toString().replace("-", ""));
                refundFlow.setCreatedAt(LocalDateTime.now());
                refundFlow.setCompletedAt(LocalDateTime.now());
                refundFlow.setTransactionsStatus("退款成功");
                refundFlow.setAmount(refundAmount);
                refundFlow.setCompletedType("退款");
                orderTransactionsMapper.insert(refundFlow);

                return Result.getSuccess("退款成功");
            } else {
                System.err.println("退款失败, 错误信息: " + response.getSubMsg());

                refunds.setRefundStatus("退款失败");
                refunds.setCompleteTime(LocalDateTime.now());
                refundsMapper.updateById(refunds);

                return Result.getFail("退款失败：" + response.getSubMsg());
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.getFail("支付宝接口调用异常：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.getFail("系统异常：" + e.getMessage());
        }
    }


}
